package com.zgr.ssh.dao.daoimpl;

import com.zgr.ssh.dao.IPlantDao;
import com.zgr.ssh.entity.Plant;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Transactional
public class PlantDaoImpl implements IPlantDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Plant> getPlantIsUp() {
        Session session = getSession();
        String hql = "FROM Plant";
        Query query = session.createQuery(hql);
        List<Plant> list = query.list();
        for (Plant plant: list) {
            System.out.println(plant);
        }
        return list;
    }

    @Override
    public void upLine(Integer id) {
        System.out.println("id = " + id);
        Session session = getSession();
        String hql = "UPDATE Plant SET rfid=:rfid,is_up=1 WHERE id=:id";
        Query queryUpdate = session.createQuery(hql);
        queryUpdate.setParameter("rfid","0025");
        queryUpdate.setParameter("id",id);
        int ret = queryUpdate.executeUpdate();
        System.out.println("ret= " + ret);
    }

    @Override
    public void downLine(Integer id) {
        Session session = getSession();
        String hql = "UPDATE Plant SET rfid=null,isUp=0 WHERE id=:id";
        Query queryUpdate = session.createQuery(hql);
        queryUpdate.setParameter("id",id);
        int ret = queryUpdate.executeUpdate();
        System.out.println("ret= " + ret);
    }

    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }
}
